﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebUtils.Models;
using Av.Utils;

namespace WebUtils.ViewModels
{
    public class LvtListViewModel
    {

        protected List<Lvt> _listValuesTree = new List<Lvt>();
        protected int _autoId = -1;
        protected int _listId = -1;
        protected SymCsmLng _lng = SymCsmLng.Lt;

        public void ParseText(string[] lines)
        {
            _listValuesTree.Clear();

            Log4cs.Log("Parsing {0} lines to prepare for list_values_tree...", lines.Length);
            for(int i = 0; i < lines.Length; i++)
            {
                if(string.IsNullOrEmpty(lines[i]) || lines[i].StartsWith("#"))
                {
                    Log4cs.Log(Importance.Debug, "Line #{0} is empty or commented", (i + 1));
                }
                else
                {
                    Lvt lvt = new Lvt();
                    lvt.Value = lines[i].Trim();
                    _listValuesTree.Add(lvt);
                }
            }
            Log4cs.Log("{0} LVT are parsed", _listValuesTree.Count);
        }

        public string PrepareSql()
        {
            StringBuilder sb = new StringBuilder();
            foreach(Lvt lvt in _listValuesTree)
            {
                if( _listId > 0 )
                {
                    lvt.ListId = _listId;
                }
                if( _autoId > 0 )
                {
                    lvt.Id = _autoId++;
                }
                sb.AppendLine(lvt.ToSql());
            }
            return sb.ToString();
        }

        public void ParseAutoId(string nr)
        {
            int autoId = 0;
            if( int.TryParse(nr, out autoId) == false )
            {
                throw new ArgumentException("Autoincremented ID should be number!");
            }

            if(autoId < 0)
            {
                throw new ArgumentOutOfRangeException("Autoincremented ID should be greater than 0!");
            }

            _autoId = autoId;
        }

        public void ParseListId(string nr)
        {
            int temp = 0;
            if(int.TryParse(nr, out temp) == false)
            {
                throw new ArgumentException("ID of LVT should be number!");
            }

            if(temp < 0)
            {
                throw new ArgumentOutOfRangeException("ID of LVT should be greater than 0!");
            }

            _listId = temp;
        }
    }
}
